﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Host.Models;

namespace Host.Controllers
{
    public class SystemController : Controller
    {
        private static string SessionClientModel = "clientModel";
        private static string SessionClientContractModel = "clientModel";

        public const int ClientPageSize = 10;
        public const int ClientContractPageSize = 10;

        private ClientModel _clientModel = new ClientModel();
        private ClientContractModel _clientContractModel = new ClientContractModel();

        /// <summary>
        /// View to administrate the clients in the system
        /// </summary>
        /// <returns>View</returns>
        [Authorize(Roles = "Administrator, Developer")]
        public ViewResult Clients(ClientModel model, int? page )
        {
            ModelState.Remove("Active");
            if(model.Update)
            {
                UpdateClient(model);
                model = new ClientModel().GetData(0, ClientPageSize); 
                return View("Clients", model);
            }
            ClientModel dirty = model;
            if (model.ClientId != 0)
                Session[SessionClientModel] = model;

            if (Session[SessionClientModel] != null)
                model = (ClientModel)Session[SessionClientModel];

            int startPage = 0;
            if (page.HasValue && page.Value > 0)
                startPage = page.Value - 1;

            _clientModel = new ClientModel().GetData(startPage, ClientPageSize);

            if (model.ClientId != 0)
                UpdateClient(dirty);

            return View(_clientModel);
        }


       

       /// <summary>
       /// Persist the client changes 
       /// </summary>
        /// <param name="model" value="ClientModel">ClientModel Object</param>
       /// <returns>View</returns>
        public void UpdateClient(ClientModel model)
        {
            new ClientModel().UpdateClient(model);
            model = new ClientModel().GetData(0, ClientPageSize); 
            Session[SessionClientModel] = model;
           
        }


        /// <summary>
        /// View to administrate the clients in the system
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles = "Administrator, Developer")]
        public ViewResult ClientContracts(ClientContractModel model, int? page) {
            //SessionClientContractModel
            int startPage = 0;
            if (page.HasValue && page.Value > 0)
                //startPage = page.Value = -1;
            _clientContractModel = new ClientContractModel().GetData(startPage, ClientContractPageSize);
            return View(_clientContractModel);
        }
    }
}
